﻿
using System;
using System.Collections.Generic;
using System.Linq;

namespace Okarito.Utility
{
    public static class EnumerableUtility
    {
        /// <summary>
        /// Computes the sum of a sequence of <see cref="TimeSpan"/> values.
        /// </summary>
        /// <param name="source">A sequence of <see cref="TimeSpan"/> values to calculate the sum of.</param>
        /// <returns>The total duration of the values in the sequence.</returns>
        public static TimeSpan Sum(this IEnumerable<TimeSpan> source)
        {
            TimeSpan total = TimeSpan.Zero;
            foreach (TimeSpan span in source)
                total += span;
            return total;
        }

        /// <summary>
        /// Computes the sum of a sequence of <see cref="TimeSpan"/> values that are obtained by
        /// invoking a transform function on each element of the input sequence.
        /// </summary>
        /// <param name="source">A sequence of values that are used to calculate a sum.</param>
        /// <param name="selector">A transform function to apply to each element.</param>
        /// <returns>The total duration of the values in the sequence.</returns>
        public static TimeSpan Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, TimeSpan> selector)
        {
            return source.Aggregate(TimeSpan.Zero, (total, value) => total + selector(value));
        }
    }
}
